//
//  LBPolarPixellatePosterizeFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/14/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#include <iostream>
#include "LBPolarPixellatePosterizeFilter.h"
#include "LBProgram.h"
#include "LBStruct.h"
#include "LBUtils.h"
#include "LBTexture.h"
#include "LBGraphics.h"

char fShaderStrPolar[] = ""
"precision mediump float;"
"varying vec2 vtexCoor;  "
"uniform vec2 center; "
"uniform vec2 pixelSize;  "
"uniform sampler2D texture;   "

"void main()    "
"{              "
"highp vec2 normCoord = 2.0 * vtexCoor - 1.0;     "
"highp vec2 normCenter = 2.0 * center - 1.0;    "

"normCoord -= normCenter;    "

"highp float r = length(normCoord); // to polar coords    \n"
"highp float phi = atan(normCoord.y, normCoord.x); // to polar coords    \n"

"r = r - mod(r, pixelSize.x) + 0.03;    "
"phi = phi - mod(phi, pixelSize.y);    "

"normCoord.x = r * cos(phi);    "
"normCoord.y = r * sin(phi);    "

"normCoord += normCenter;    "

"mediump vec2 textureCoordinateToUse = normCoord / 2.0 + 0.5;    "
"mediump vec4 color = texture2D(texture, textureCoordinateToUse );    "

"color = color - mod(color, 0.1);    "
"gl_FragColor = color;    "

"}    "
;

LBPolarPixellatePosterizeFilter::LBPolarPixellatePosterizeFilter(){
    init(0, fShaderStrPolar);
    
    LBGraphics::getInstance()->useProgram(program);
    
    centerUniform = program->uniformIndex("center");
    pixelSizeUniform = program->uniformIndex("pixelSize");
    
    
    setCenter(0.5, 0.5);
    setPixelSize(0.05, 0.05);
}

LBPolarPixellatePosterizeFilter::LBPolarPixellatePosterizeFilter(float xCenter, float yCenter, float xPixelSize, float yPixelSize){
    init(0, fShaderStrPolar);
    
    centerUniform = program->uniformIndex("center");
    pixelSizeUniform = program->uniformIndex("pixelSize");

    setCenter(xCenter, yCenter);
    setPixelSize(xPixelSize, yPixelSize);
}

LBPolarPixellatePosterizeFilter::~LBPolarPixellatePosterizeFilter(){
}

void LBPolarPixellatePosterizeFilter::setCenter(float xCenter, float yCenter){
    center.one = xCenter;
    center.two = yCenter;
    LBGraphics::getInstance()->useProgram(program);
    glUniform2f(centerUniform, xCenter, yCenter);
}

void LBPolarPixellatePosterizeFilter::setPixelSize(float xPixelSize, float yPixelSize){
    pixelSize.one = xPixelSize;
    pixelSize.two = yPixelSize;
    LBGraphics::getInstance()->useProgram(program);    
    glUniform2f(pixelSizeUniform, xPixelSize, yPixelSize);
}
